/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.facilscrum.form.backlog;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import org.facilscrum.beans.Backlog;
import org.javscaz.javscaztools.utilidades.Utilidades;
import org.facilscrum.beans.Userstories;
import org.facilscrum.controller.ProyectosController;
import org.facilscrum.controller.UserstoriesController;
import org.facilscrum.form.usuarios.UsuariosForm;
import org.facilscrum.generales.Mensajeria;
import org.facilscrum.sesion.MySesion;
import org.javscaz.javscaztools.tablas.CustomEditor;
import org.javscaz.javscaztools.tablas.CustomRenderer;

/**
 *
 * @author avbravo
 */
public class BacklogForm extends javax.swing.JInternalFrame {

    ProyectosController proyectosController = new ProyectosController();
    UserstoriesController userstoriesController = new UserstoriesController();
    DefaultTableModel modelo;
    List<Backlog> listBacklog = new ArrayList<>();

    /**
     * Creates new form BacklogForm
     */
    public BacklogForm() {
        initComponents();
        modelo = (DefaultTableModel) jTable1.getModel();
        if (!MySesion.getSeleccionoProyectoTrabajo()) {
            Mensajeria.MensajeWarning("Debe indicar el proyecto de trabajo");
        } else {

            jTextFieldProyecto.setText(MySesion.getProyectos().getProyecto());
            cargarUserstories();
        }
        TableColumn columna = jTable1.getColumnModel().getColumn(0);
        columna.setCellRenderer(new CustomRenderer());
        columna.setCellEditor(new CustomEditor());
        jTable1.setRowHeight(70);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldProyecto = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldTotalPuntos = new javax.swing.JTextField();
        jButtonImprimir = new javax.swing.JButton();
        jLabelMensaje = new javax.swing.JLabel();
        jButtonCerrar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Backlog");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Proyecto");

        jTextFieldProyecto.setEnabled(false);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "userstories"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setText("Total de puntos");

        jTextFieldTotalPuntos.setEnabled(false);

        jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/facilscrum/gif/x16/print.png"))); // NOI18N
        jButtonImprimir.setEnabled(false);
        jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirActionPerformed(evt);
            }
        });

        jLabelMensaje.setText("Mensaje:");

        jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/avbravo/jscrum/gif/return.gif"))); // NOI18N
        jButtonCerrar.setToolTipText("Cerrar");
        jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCerrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addComponent(jButtonImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldTotalPuntos, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 671, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 524, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelMensaje)
                .addGap(3, 3, 3)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonImprimir)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jTextFieldTotalPuntos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButtonCerrar))
                .addGap(54, 54, 54))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 28, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirActionPerformed
        HashMap map = new HashMap();
map.put("p_proyecto",MySesion.getProyectos().getProyecto());
map.put("p_puntos",jTextFieldTotalPuntos.getText());
        try {
            imprimir(listBacklog, map);
        } catch (JRException ex) {
            Mensajeria.MensajeError(ex, "imprimir()");
        }
    }//GEN-LAST:event_jButtonImprimirActionPerformed

    private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCerrarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCerrar;
    private javax.swing.JButton jButtonImprimir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelMensaje;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldProyecto;
    private javax.swing.JTextField jTextFieldTotalPuntos;
    // End of variables declaration//GEN-END:variables

    private void imprimir(List<Backlog> aux, HashMap map) throws JRException {
        try {
            JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(aux);
//Indicamos la ruta del reporte
            InputStream reporte = (InputStream) getClass().getResourceAsStream("/org/facilscrum/reportes/backlog.jasper");
            if (reporte == null) {
                Mensajeria.Mensaje("No se pudo cargar el reporte");
            } else {
                JasperPrint print = JasperFillManager.fillReport(reporte, map, ds);
                JasperViewer.viewReport(print, false);
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Imprimir()");
        }
    }

    private Boolean cargarUserstories() {
        try {
            jTextFieldTotalPuntos.setText("");
            listBacklog.removeAll(listBacklog);
            Integer totalPuntos = 0;
            modelo = Utilidades.limpiarModelo(modelo);
            if (userstoriesController.query("asignado='no' and idproyecto='" + MySesion.getProyectos().getIdproyecto() + "' order by importancia desc")) {
                for (Userstories u : userstoriesController.getUserstorieslist()) {
                    Object[] filas = new Object[5]; // Hay tres columnas en la tabla       
                    String texto = "[" + u.getIduserstories() + "]" + u.getNombre() + "\nImportancia(" + u.getImportancia() + ") Puntos(" + u.getPuntos() + ")\n" + u.getUsuarios().getUsername();
                    filas[0] = texto;
                    totalPuntos += u.getPuntos();
                    Backlog backlog = new Backlog(texto, totalPuntos);
                    listBacklog.add(backlog);
                    modelo.addRow(filas);
                }
                jButtonImprimir.setEnabled(true);
            } else {
                jLabelMensaje.setText("No hay user stories con el estatus no asignado para este proyecto");
            }
            jTextFieldTotalPuntos.setText(totalPuntos.toString());

        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "cargarUserstories()");
        }
        return null;
    }
}
